<?php
define("CONTRACT_UPLOAD_DIR", WWW_ROOT.'files'.DS.'contract');
/*
 * Contracts Controller class
 * PHP versions 5.1.4
 * @filesource
 * @author   Manisha/Reetu
 * @version 0.0.1 
 *   - Initial release 
 */

class ContractsController extends AppController {
    public $uses = array('User', 'Contract');
    
    /* __________________________________________________________
     * @Method      :beforeFilter
     * @Description :to set up the Auth component
     * @access      :null
     * @param      :null
     * @return     :null
     */
    function beforeFilter() {
        //--------- Directory Creation------------
        if (!is_dir(CONTRACT_UPLOAD_DIR)) {
            mkdir(CONTRACT_UPLOAD_DIR, 0777);         
        }
        $this->layout = 'home';
        parent::beforeFilter();
    }
    
    /* 
     * @Method      :index
     * @Description :to List contracts
     * @access      :null
     * @param      :null
     * @return     :null
     */
    public function index($batch_list_id = null) {
        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');
        
        if (!$batch_list_id) {
            throw new NotFoundException(__('INVALID_BATCH'));
        }
        
        App::Import("Model", "BatchList");
        $this->BatchList = new BatchList();
        $this->BatchList->recursive = -1;
        $batchData = $this->BatchList->findById($batch_list_id);
        
        if (!$batchData) {
            throw new NotFoundException(__('INVALID_BATCH'));
        }
        
        $conditions = array();
        $conditions['Contract.batch_list_id'] = $batch_list_id;
        if ($this->request->data) {
            if (isset($this->data['Contract']['search_criteria']) && $this->data['Contract']['search_criteria'] != '') {
                $searchCriteriaTerm = trim($this->data['Contract']['search_criteria']);
                $conditions['Contract.title LIKE '] = "%" . $searchCriteriaTerm . "%";
            } 
        } 

        $contractData = $this->paginate('Contract', array($conditions));
        $this->set('contractData', $contractData);
        $this->set('batch_list_id' , $batch_list_id);
        
        if ($this->request->is('ajax')) {
            $this->viewPath = 'elements' . DS . 'contracts';
            $this->render('list', 'ajax');
        }//if
    }
    
    
    /* 
     * @Method      :index
     * @Description :to List contracts
     * @access      :null
     * @param      :null
     * @return     :null
     */
    public function admin_verification_index($batch_list_id = null) {
        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');
        
        if (!$batch_list_id) {
            throw new NotFoundException(__('INVALID_BATCH'));
        }
        
        App::Import("Model", "BatchList");
        $this->BatchList = new BatchList();
        $this->BatchList->recursive = -1;
        $batchData = $this->BatchList->findById($batch_list_id);
        
        if (!$batchData) {
            throw new NotFoundException(__('INVALID_BATCH'));
        }
        
        //criteria array for search
        $crit = array();
        $crit[] = "";

        if ($this->request->data) {
            if (isset($this->data['Contract']['search_criteria']) && $this->data['Contract']['search_criteria'] != '') {
                $searchCriteriaTerm = trim($this->data['Contract']['search_criteria']);
                $conditions = array(
                    'Contract.title LIKE ' => "%" . $searchCriteriaTerm . "%",
                    'Contract.batch_list_id' => $batch_list_id,
                );
            }
        } else{
            $conditions = array(
                'Contract.batch_list_id' => $batch_list_id,
            );
        }

        $contractData = $this->paginate('Contract', array($conditions));
        $this->set('contractData', $contractData);
        $this->set('batch_list_id' , $batch_list_id);
        
        if ($this->request->is('ajax')) {
            $this->viewPath = 'elements' . DS . 'contracts';
            $this->render('admin_verification_list', 'ajax');
        }//if
    }
    /* 
     * @Method      :download
     * @Description :to List contracts
     * @access      :null
     * @param      :null
     * @return     :null
     */
    public function download($id = null) {
        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');

        if (!$id) {
            throw new NotFoundException(__('INVALID_CONTRACT'));
        }
        $contractData = $this->Contract->findById($id);

        if (!$contractData) {
            throw new NotFoundException(__('INVALID_CONTRACT'));
        }
        
        $file_extension = pathinfo($contractData['Contract']['path']);
        switch( $file_extension['extension'] ){
            case "doc": $ctype="application/msword"; break;
            case ".docx": $ctype="application/msword"; break;
            default: $ctype="application/force-download";
        }
        
        $fileNameNew = CONTRACT_UPLOAD_DIR.DS.$contractData['Contract']['title'];
        $fileName = CONTRACT_UPLOAD_DIR.DS.$contractData['Contract']['path'];
        header("Pragma: public"); // required
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private",false); // required for certain browsers 
        header("Content-Type: $ctype");
        // change, added quotes to allow spaces in filenames, by Rajkumar Singh
        header("Content-Disposition: attachment; filename=\"".basename($fileNameNew).'.'.$file_extension['extension']."\";" );
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: ".filesize($fileName));
        readfile($fileName);
        exit();
    }

    /* 
     * @Method      :index
     * @Description :to List contracts
     * @access      :null
     * @param      :null
     * @return     :null
     *
    public function admin_index() {
        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');

        $savecrit = '';

        //criteria array for search
        $crit = array();
        $crit[] = "";

        if (isset($this->data)) {

            if (isset($this->data['Contract']['search_criteria']) && $this->data['Contract']['search_criteria'] != '') {
                $searchCriteriaTerm = trim($this->data['Contract']['search_criteria']);
                //will search with name and abbreviation
                $crit[] = "(Contract.title like '%" . $searchCriteriaTerm . "%')";
                $savecrit .= "search_criteria:" . $searchCriteriaTerm . "/";
            }
        }
        //for passing the values of search conditions in params of paging to next page
        if (count($this->params['named']) > 0) {
            foreach ($this->params['named'] as $paramKey => $paramValue) {
                $savecrit .= $paramKey . ":" . $paramValue . "/";
            }
            if (isset($this->params['named']['search_criteria'])){
                $crit[] = "(Contract.eng_name like '%" . $this->params['named']['search_criteria'] . "%')";
            }
        }//if
        if (count($crit) > 0) {
            $criteria = implode("1 AND ", $crit);
        } else {
            $criteria = "";
        }

        $contractData = $this->paginate('Contract', array($criteria));
        $this->set('contractData', $contractData);

        if ($this->request->is('ajax')) {
            $this->viewPath = 'elements' . DS . 'contracts';
            $this->render('admin_list', 'ajax');
        }//if
    }*/
    
    /* 
     * @Method      :add
     * @Description :to add contracts
     * @access      :null
     * @param      :null
     * @return     :null
     */
    public function add($batch_list_id = null) {
        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');
        
        if (!$batch_list_id) {
            throw new NotFoundException(__('INVALID_BATCH'));
        }
        
        App::Import("Model", "BatchList");
        $this->BatchList = new BatchList();
        $this->BatchList->recursive = -1;
        $batchData = $this->BatchList->findById($batch_list_id);
        
        if (!$batchData) {
            throw new NotFoundException(__('INVALID_BATCH'));
        }
        
        $this->set('batch_list_id' , $batch_list_id);
        
        if ($this->request->is('post')) {
            $this->Contract->create();
            if (isset($this->request->data['Contract']['path'])) {
                $tmp_name = $this->request->data['Contract']['path']["tmp_name"];
                $name = $this->request->data['Contract']['path']["name"];
                $newFileName = time().'_'.str_replace(" ", "_", $name);
                
                if (move_uploaded_file($tmp_name, CONTRACT_UPLOAD_DIR . DS . $newFileName)) {
                    $this->request->data['Contract']['path'] = $newFileName;
                    
                    if($this->Contract->save($this->request->data)){
                        $contract_id = $this->Contract->getLastInsertID();
                        $this->saveActionLog('contract', 'Contract Added ID :'. $contract_id);
                        $msg = __("CONTRACT_ADD_SUCCESS", true);
                        $this->Session->setFlash('<div class="totalSuccess">' . $msg . '</div>');
                        return $this->redirect(array('action' => 'index/'.$batch_list_id));
                    } else {
                        if(isset($this->Contract->validationErrors['path'])){
                            $msg = __("ONLY_PDF_FILE", true);
                            $this->Session->setFlash('<div class="totalErrors">' . $msg . '</div>');
                        }
                    }
                }
            }
        }
    }
    
    /* 
     * @Method      :edit
     * @Description :to Edit contracts
     * @access      :null
     * @param      :null
     * @return     :null
     */
    public function edit($id = null, $batch_list_id = null) {
        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');
        
        if (!$batch_list_id) {
            throw new NotFoundException(__('INVALID_BATCH'));
        }
        
        App::Import("Model", "BatchList");
        $this->BatchList = new BatchList();
        $this->BatchList->recursive = -1;
        $batchData = $this->BatchList->findById($batch_list_id);
        
        if (!$batchData) {
            throw new NotFoundException(__('INVALID_BATCH'));
        }
        
        $this->set('batch_list_id' , $batch_list_id);
        
        if (!$id) {
            throw new NotFoundException(__('INVALID_CONTRACT'));
        }
        $contractData = $this->Contract->findById($id);
        $oldFileName = $contractData['Contract']['path'];
        
        if (!$contractData) {
            throw new NotFoundException(__('INVALID_CONTRACT'));
        }
        
        if ($this->request->is(array('Contract', 'put'))) {
            $this->Contract->id = $id;
            
            /*if ($this->request->data['Contract']['path']['name']) {
                $data = array();
                $tmp_name = $this->request->data['Contract']['path']["tmp_name"];
                $name = $this->request->data['Contract']['path']["name"];
                $newFileName = time().'_'.str_replace(" ", "_", $name);
                
                if (move_uploaded_file($tmp_name, CONTRACT_UPLOAD_DIR . DS . $newFileName)) {
                    $this->request->data['Contract']['path'] = $newFileName;
                }
            } else {
                unset($this->request->data['Contract']['path']);
            }*/
            
            if($this->Contract->save($this->request->data)){
                $this->deleteFile($oldFileName);
                $msg = __("CONTRACT_UPDATE_SUCCESS", true);
                $this->Session->setFlash('<div class="totalSuccess">' . $msg . '</div>');
                return $this->redirect(array('action' => 'index/'.$batch_list_id));
            } else {
                if(isset($this->Contract->validationErrors['path'])){
                    $msg = __("ONLY_PDF_FILE", true);
                    $this->Session->setFlash('<div class="totalErrors">' . $msg . '</div>');
                }
            }
        }
        
        if (!$this->request->data) {
            $this->request->data = $contractData;
        }
    }
    
    public function delete($id = null, $batch_list_id = null){
        $userId = $this->Auth->User("id");
        $userType = $this->Auth->User('user_type');

        if (!$id) {
            throw new NotFoundException(__('INVALID_CONTRACT'));
        }
        $contractDetails = $this->Contract->findById($id);
        $oldFileName = $contractDetails['Contract']['path'];
        
        if (!$contractDetails) {
            throw new NotFoundException(__('INVALID_CONTRACT'));
        }
        //--- delete Payee---------
        $contractCondition = array('Contract.id' => $id);
        $this->Contract->delete($contractCondition, FALSE);
        $this->deleteFile($oldFileName);
        
        $this->saveActionLog('contract', 'Contract Deleted ID :'. $id);
        
        $conditions = array(
            'Contract.batch_list_id' => $batch_list_id,
        );
        
        $contractData = $this->paginate('Contract', array($conditions));
        $this->set('contractData', $contractData);
        $this->set('batch_list_id' , $batch_list_id);
        
        $msg = __("CONTRACT_DELETE_SUCCESS", true);
        $this->Session->setFlash('<div class="totalSuccess">' . $msg . '</div>');
                        
        if ($this->request->is('ajax')) {
            $this->viewPath = 'elements' . DS . 'contracts';
            $this->render('list', 'ajax');
        }//if
    }
    
    /* 
     * @Method      :deleteFile
     * @Description :to unlink a file
     * @access      :null
     * @param      :null
     * @return     :null
     */
    function deleteFile($fileName = null){
        $fileWithPath = CONTRACT_UPLOAD_DIR . DS . $fileName;
        if (file_exists($fileWithPath)) {
            unlink($fileWithPath);
        }
    }
}